﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NGinnBPM.Lib.Interfaces;
using NGinnBPM.MessageBus.Impl.HttpService;
using NGinnBPM.MessageBus;
using System.IO;
using NGinnBPM.Lib.Schema;

namespace NGinnBPM.Services.Website
{
    
    [UrlPattern(@"^/packages/(?<id>.+)?")]
    public class PackagesServlet : ServletBase
    {
        public IProcessPackageRepository PackageRepository { get; set; }

        public override void HandleRequest(IRequestContext ctx)
        {
            ctx.ResponseContentType = "text/html";
            string pkg;
            if (ctx.UrlVariables.TryGetValue("id", out pkg) && pkg.Length > 0)
            {
                OutputPackageInfo(pkg,ctx);
            }
            else
            {
                ctx.Output.WriteLine("<html><body><div>Installed packages: {0}</div>", PackageRepository.PackageNames.Count);
                ctx.Output.WriteLine("<div><ol>");
                foreach (string pn in PackageRepository.PackageNames)
                {
                    ctx.Output.WriteLine("<li><a href='./{0}'>{0}</a></li>", pn);
                }
                ctx.Output.WriteLine("</ol></div>");
                ctx.Output.WriteLine("</body></html>");
            }
        }

        protected void OutputPackageInfo(string pkgname, IRequestContext ctx)
        {
            PackageDefinition pd = PackageRepository.GetPackage(pkgname);
            ctx.Output.WriteLine("<div><h2>Package: {0}</h2></div>", pd.Name);
            ctx.Output.WriteLine("<div>Process definitions in package:<br/><ol>");
            foreach (string dn in pd.ProcessDefinitionNames)
            {
                ctx.Output.WriteLine("<li><a href='../processdef/{0}.{1}'>{1}</a><br/>", pkgname, dn);
                ctx.Output.WriteLine("<p>Xml data schemas: <a href='/schema/{0}/in'>input</a>, <a href='/schema/{0}/out'>output</a>, <a href='/schema/{0}/internal'>internal</a></p></li>", pd.Name + "." + dn);
            }
            ctx.Output.WriteLine("</ol></div>");
            ctx.Output.WriteLine("<a href='./?reload'>Reload this package</a>");
        }
    }
}
